import React, { Component } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Tabs, DatePicker } from 'antd';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import numeral from 'numeral';
import styles from './Analysis.less';
import { Bar } from '@/components/Charts';

// 引入 ECharts 主模块
import echarts from 'echarts';
// 引入柱状图
import 'echarts/lib/chart/bar';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/map/js/china';
import 'echarts/map/js/world';

import { geoCoordMap, nameMap } from '@/Constants/geoCoordMap';
import { worldChinaMap } from '@/Constants/worldChina';

let myChart = null;

@connect(() => ({}))
class SalesMap extends Component {
  state = {
    airLines: [],
  };
  divRef = React.createRef();

  planePath =
    'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z';

  color = [
    '#a6c84c',
    '#eb2100',
    '#eb3600',
    '#d0570e',
    '#d0a00e',
    '#34da62',
    '#00c0e9',
    '#0096f3',
    '#33CCFF',
    '#33FFCC',
    '#FFC22D',
    '#1B9EFF',
    '#FF596F',
    '#3ed4ff',
    '#ffa022',
  ];

  provieName = [
    '北京',
    '天津',
    '上海',
    '重庆',
    '河北',
    '河南',
    '云南',
    '辽宁',
    '黑龙江',
    '湖南',
    '安徽',
    '山东',
    '新疆',
    '江苏',
    '浙江',
    '江西',
    '湖北',
    '广西',
    '甘肃',
    '山西',
    '内蒙古',
    '陕西',
    '吉林',
    '福建',
    '贵州',
    '广东',
    '青海',
    '西藏',
    '四川',
    '宁夏',
    '海南',
    '台湾',
    '香港',
    '澳门',
  ];

  namedata = [
    { name: '张' },
    { name: '刘' },
    { name: '李' },
    { name: '邓' },
    { name: '熊' },
    { name: '田' },
    { name: '周' },
    { name: '赵' },
    { name: '钱' },
    { name: '孙' },
    { name: '吴' },
    { name: '郑' },
    { name: '王' },
    { name: '冯' },
    { name: '陈' },
    { name: '杨' },
    { name: '朱' },
    { name: '秦' },
    { name: '许' },
    { name: '徐' },
    { name: '何' },
    { name: '曹' },
    { name: '陶' },
    { name: '邹' },
    { name: '苏' },
    { name: '范' },
    { name: '彭' },
    { name: '鲁' },
    { name: '马' },
    { name: '方' },
    { name: '唐' },
    { name: '顾' },
  ];

  getTargeArray = airLines => {
    const newAirLinesArray = airLines.map(val => {
      return [val[0][0].name, val];
    });
    return newAirLinesArray;
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'dashboard/fetchAirline' }).then(res => {
      if (res.errorCode === 0) {
        this.setState({
          airLines: res.data,
        });
        let series = [];
        Array.from(this.getTargeArray(res.data)).forEach((item, i) => {
          series.push(
            {
              name: item[0] + ' Top10',
              type: 'lines',
              zlevel: 1,
              effect: {
                show: true,
                period: Math.floor(Math.random() * 3 + 5),
                delay: Math.floor(Math.random() * 100 + 20),
                trailLength: 0,
                symbol: this.planePath,
                color: this.color[i],
                symbolSize: 13,
              },
              lineStyle: {
                normal: {
                  color: this.color[7],
                  width: 1.4,
                  opacity: 0.4,
                  curveness: 0.2,
                },
              },
              data: this.convertData(item[1]),
            },
            {
              name: item[0] + ' Top10',
              type: 'effectScatter',
              coordinateSystem: 'geo',
              zlevel: 1,
              rippleEffect: {
                brushType: 'stroke',
              },
              label: {
                normal: {
                  show: true,
                  position: 'right',
                  formatter: '{b}',
                  textBorderColor: 'none',
                  color: '#fff',
                },
              },
              symbolSize: function(val, params) {
                if (['西安市', '海口市', '上海市'].includes(params.name)) {
                  return 14;
                }
                return 11;
              },
              itemStyle: {
                normal: {
                  color: '#00e9db',
                },
              },
              data: item[1].map(dataItem => {
                return {
                  name: dataItem[1].name,
                  value: geoCoordMap[dataItem[1].name].concat([dataItem[1].value]),
                };
              }),
            }
          );
        });
        const geoSeries = [
          {
            type: 'effectScatter',
            coordinateSystem: 'geo',
            z: 10,
            zlevel: 10,
            data: [],
            symbol: 'triangle',
            animationEasingUpdate: 'elasticOut',
            label: {
              normal: {
                show: true,
                formatter: function(params) {
                  return (
                    '{fline|客户：' +
                    params.data.username +
                    '  ' +
                    params.data.telphone +
                    '}\n{tline|' +
                    params.data.address +
                    '}'
                  );
                },
                position: 'top',
                backgroundColor: 'rgba(254,174,33,0.9)',
                padding: [0, 0],
                borderRadius: 3,
                lineHeight: 32,
                color: '#f7fafb',
                rich: {
                  fline: {
                    padding: [0, 10, 10, 10],
                    fontSize: 14,
                    color: '#ffffff',
                  },
                  tline: {
                    padding: [10, 10, 0, 10],
                    fontSize: 14,
                    color: '#ffffff',
                  },
                },
              },
              emphasis: {
                show: true,
              },
            },
            itemStyle: {
              color: '#feae21',
            },
          },
          {
            type: 'effectScatter',
            coordinateSystem: 'geo',
            z: 11,
            zlevel: 11,
            animationEasingUpdate: 'elasticOut',
            symbol: 'triangle',
            data: [],
            label: {
              normal: {
                show: true,
                formatter: function(params) {
                  return (
                    '{fline|客户：' +
                    params.data.username +
                    '  ' +
                    params.data.telphone +
                    '}\n{tline|' +
                    params.data.address +
                    '}'
                  );
                },
                position: 'top',
                backgroundColor: 'rgba(233,63,66,0.9)',
                padding: [0, 0],
                borderRadius: 3,
                lineHeight: 32,
                color: '#ffffff',
                rich: {
                  fline: {
                    padding: [0, 10, 10, 10],
                    fontSize: 14,
                    color: '#ffffff',
                  },
                  tline: {
                    padding: [10, 10, 0, 10],
                    fontSize: 14,
                    color: '#ffffff',
                  },
                },
              },
              emphasis: {
                show: true,
              },
            },
            itemStyle: {
              color: '#e93f42',
            },
          },
          {
            type: 'effectScatter',
            coordinateSystem: 'geo',
            animationEasingUpdate: 'elasticOut',
            z: 12,
            zlevel: 12,
            data: [],
            symbol: 'triangle',
            label: {
              normal: {
                show: true,
                formatter: function(params) {
                  return (
                    '{fline|客户：' +
                    params.data.username +
                    '  ' +
                    params.data.telphone +
                    '}\n{tline|' +
                    params.data.address +
                    '}'
                  );
                },
                position: 'top',
                backgroundColor: 'rgba(8,186,236,0.8)',
                padding: [0, 0],
                borderRadius: 3,
                lineHeight: 32,
                color: '#ffffff',
                rich: {
                  fline: {
                    padding: [0, 10, 10, 10],
                    fontSize: 14,
                    color: '#ffffff',
                  },
                  tline: {
                    padding: [10, 10, 0, 10],
                    fontSize: 14,
                    color: '#ffffff',
                  },
                },
              },
              emphasis: {
                show: true,
              },
            },
            itemStyle: {
              color: '#08baec',
            },
          },
        ];
        const regionsData = this.provieName.map(val => {
          return {
            name: val,
            itemStyle: {
              areaColor: '#20336D',
              borderColor: '#1A62BC',
            },
            emphasis: {
              areaColor: '#26439D',
              borderColor: '#2B73CC',
            },
          };
        });
        const option = {
          backgroundColor: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#101239', // 0% 处的颜色
              },
              {
                offset: 1,
                color: '#120434', // 100% 处的颜色
              },
            ],
            global: false,
          },
          tooltip: {
            trigger: 'item',
          },

          geo: {
            map: 'world',
            nameMap: nameMap,
            label: {
              emphasis: {
                show: false,
              },
            },
            roam: false,
            center: [102.97, 35.91],
            zoom: 4.9,
            itemStyle: {
              normal: {
                areaColor: '#1E2C57',
                borderColor: '#1C569E',
              },
              emphasis: {
                areaColor: '#26439D',
                borderColor: '#2B73CC',
              },
            },
            label: {
              show: true,
              color: '#3D96FF',
              emphasis: {
                color: '#fff',
              },
            },
            regions: regionsData,
          },
          series: [...geoSeries, ...series],
        };
        this.timer_1 = setInterval(() => {
          if (this.divRef.current) {
            myChart = echarts.init(this.divRef.current);
            echarts.registerMap('world', worldChinaMap);
            myChart.setOption(option);
            window.addEventListener('resize', function() {
              myChart.resize();
            });
            clearInterval(this.timer_1);
            // const newDataArray = res.data.flat();
            // this.timer_2 = setInterval(() => {
            //   const runidx = Math.floor(Math.random() * 3);
            //   const typeidx = Math.floor(Math.random() * 3);
            //   const dataidx = Math.floor(Math.random() * newDataArray.length);
            //   const ranval = Math.floor(Math.random() * 10);
            //   option.series[typeidx].data = [];
            //   newDataArray[dataidx][1].value = Number(newDataArray[dataidx][1].value) + ranval;
            //   const valarr = geoCoordMap[newDataArray[dataidx][1].name];
            //   valarr.push(ranval);
            //   option.series[typeidx].data = [
            //     {
            //       name: '',
            //       username: this.getName(runidx),
            //       telphone: this.getTel(),
            //       address: this.getAddress(dataidx, typeidx),
            //       value: valarr,
            //     },
            //   ];
            //   myChart.setOption(option, true);
            // }, 5000);
          }
        }, 0);
      }
    });
  }

  componentWillUnmount() {
    this.timer_1 && clearInterval(this.timer_1);
    this.timer_2 && clearInterval(this.timer_2);
  }
  getTel = () => {
    let n = 2,
      telstr = '1';
    while (n < 12) {
      if (n < 3) {
        while (1) {
          let nums = Math.floor(Math.random() * 10);
          if (nums !== 0 && nums !== 1 && nums !== 2 && nums !== 3 && nums !== 4 && nums !== 6) {
            telstr += nums;
            break;
          }
        }
      } else if (n > 3 && n < 8) {
        telstr += '*';
      } else {
        telstr += Math.floor(Math.random() * 10);
      }
      n++;
    }
    return telstr;
  };

  getName = type => {
    let name = '';
    const roundnum = Math.floor(Math.random() * 32);
    switch (type) {
      case 1:
        name = this.namedata[roundnum].name + '先生';
        break;
      case 2:
        name = this.namedata[roundnum].name + '女士';
        break;
      default:
        name = this.namedata[roundnum].name + '先生';
        break;
    }
    return name;
  };
  getAddress = (num, type) => {
    const { airLines } = this.state;
    const newDataArray = airLines.flat();
    let addstr = '';
    switch (type) {
      case 1:
        addstr =
          '有' +
          (Math.random() * 5).toFixed(2) +
          '吨货物在' +
          newDataArray[num][1].name +
          '【已发货】';
        break;
      case 2:
        addstr =
          '有' +
          (Math.random() * 3).toFixed(2) +
          '吨货物在' +
          newDataArray[num][1].name +
          '【运输中】';
        break;
      default:
        addstr =
          '有' +
          (Math.random() * 2).toFixed(2) +
          '吨货物在' +
          newDataArray[num][1].name +
          '【已签收】';
        break;
    }
    return addstr;
  };

  convertData = data => {
    let res = [];
    for (let i = 0; i < data.length; i++) {
      const dataItem = data[i];
      const fromCoord = geoCoordMap[dataItem[0].name];
      const toCoord = geoCoordMap[dataItem[1].name];
      if (fromCoord && toCoord) {
        res.push([
          {
            coord: fromCoord,
          },
          {
            coord: toCoord,
          },
        ]);
      }
    }
    return res;
  };

  render() {
    const { loading, height } = this.props;
    return (
      <Card loading={loading} bordered={false} bodyStyle={{ padding: 0 }}>
        <div
          style={{
            width: '100%',
            height,
            background: 'linear-gradient(180deg, rgba(16, 18, 57, 1) 0%, rgba(18, 4, 52, 1) 100%)',
          }}
          ref={this.divRef}
        />
      </Card>
    );
  }
}

export default SalesMap;
